from tqsdk import TqApi, TqAuth
import time
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 全局变量
last_open_time = {}  # 防抖计时器
account = "您的账号"  # 替换为实际账号
symbol = "SHFE.rb2401"  # 示例合约

class TradingStrategy:
    def __init__(self):
        self.api = TqApi(auth=TqAuth("您的账号", "您的密码"))
        self.quote = self.api.get_quote(symbol)

    def check_order_status(self, order_status):
        """检查订单状态"""
        if order_status in ['ALIVE', 'PARTIAL_FILLED', 'PENDING']:
            logger.warning(f"存在未完成订单: {order_status}")
            return False
        return True

    def open_position(self, symbol):
        """带防抖的开仓逻辑"""
        current_time = time.time()
        if symbol in last_open_time and current_time - last_open_time[symbol] < 5:
            logger.info(f"{symbol} 5秒内已开仓，忽略本次信号")
            return False
        
        # 实际下单逻辑（示例）
        try:
            order = self.api.insert_order(symbol, direction="BUY", offset="OPEN", volume=1)
            last_open_time[symbol] = current_time
            logger.info(f"{symbol} 开仓成功，订单ID: {order.order_id}")
            return True
        except Exception as e:
            logger.error(f"开仓失败: {e}")
            return False

    def run(self):
        """主事件循环"""
        while True:
            self.api.wait_update()
            # 这里添加您的交易信号判断逻辑
            if self.quote.last_price > self.quote.upper_limit:
                self.open_position(symbol)

if __name__ == "__main__":
    strategy = TradingStrategy()
    strategy.run()